<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: light)">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: dark)"><meta name="generator" content="Hexo 6.3.0">
<link rel="preconnect" href="https://fonts.googleapis.com" crossorigin>
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,300italic,400,400italic,700,700italic%7CZCOOL+QingKe+HuangYou:300,300italic,400,400italic,700,700italic%7CNoto+Sans+Simplified+Chinese:300,300italic,400,400italic,700,700italic%7CJetBrains+Mono:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">

<link rel="stylesheet" href="/lib/@fortawesome/fontawesome-free/css/all.min.css" integrity="sha256-HtsXJanqjKTc8vVQjO4YMhiqFoXkfBsjBWcX91T1jr8=" crossorigin="anonymous">
  <link rel="stylesheet" href="/lib/animate.css/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="/lib/@fancyapps/ui/dist/fancybox/fancybox.css" integrity="sha256-RvRHGSuWAxZpXKV9lLDt2e+rZ+btzn48Wp4ueS3NZKs=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"wyatex.online","root":"/","images":"/images","scheme":"Pisces","darkmode":true,"version":"8.18.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":true,"style":"mac"},"fold":{"enable":false,"height":500},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":true,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":true}}</script><script src="/js/config.js"></script>

    <meta name="description" content="本系列不包含 Dart 语法笔记，以掌握 Dart 语法为前提记录。不懂可以百度搜一下Dart快速入门教程，如果你本来就懂js，基本可以一两小时内掌握Dart的语法，比如看下Flutter实战上的Dart简介">
<meta property="og:type" content="article">
<meta property="og:title" content="flutter快速入门笔记（1）">
<meta property="og:url" content="https://wyatex.online/Flutter/flutterNote1/index.html">
<meta property="og:site_name" content="Wyatex&#96;s blog">
<meta property="og:description" content="本系列不包含 Dart 语法笔记，以掌握 Dart 语法为前提记录。不懂可以百度搜一下Dart快速入门教程，如果你本来就懂js，基本可以一两小时内掌握Dart的语法，比如看下Flutter实战上的Dart简介">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-11-04T06:58:06.000Z">
<meta property="article:modified_time" content="2023-09-15T10:16:22.846Z">
<meta property="article:author" content="Wyatex">
<meta property="article:tag" content="前端">
<meta property="article:tag" content="笔记">
<meta property="article:tag" content="Flutter">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://wyatex.online/Flutter/flutterNote1/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://wyatex.online/Flutter/flutterNote1/","path":"Flutter/flutterNote1/","title":"flutter快速入门笔记（1）"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>flutter快速入门笔记（1） | Wyatex`s blog</title>
  








  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">Wyatex`s blog</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">97</span></a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">26</span></a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">155</span></a></li><li class="menu-item menu-item-编程"><a href="/programming/" rel="section"><i class="fa fa-book fa-fw"></i>编程</a></li><li class="menu-item menu-item-蹲坑读物"><a href="/%E5%B9%B2%E8%B4%A7/%E5%BC%80%E5%8F%91%E4%BA%A4%E6%B5%81%E7%BE%A4%E5%88%86%E4%BA%AB%E8%AE%B0%E5%BD%95/" rel="section"><i class="fa fa-book fa-fw"></i>蹲坑读物</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%90%AF%E5%8A%A8"><span class="nav-number">1.</span> <span class="nav-text">启动</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#flutter-%E7%9A%84%E4%B8%89%E6%A3%B5%E6%A0%91"><span class="nav-number">2.</span> <span class="nav-text">flutter 的三棵树</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#StatelessWidget"><span class="nav-number">3.</span> <span class="nav-text">StatelessWidget</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#StatefulWidget"><span class="nav-number">4.</span> <span class="nav-text">StatefulWidget</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F"><span class="nav-number">5.</span> <span class="nav-text">生命周期</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%88%9B%E5%BB%BA"><span class="nav-number">5.1.</span> <span class="nav-text">创建</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%9B%B4%E6%96%B0"><span class="nav-number">5.2.</span> <span class="nav-text">更新</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%94%80%E6%AF%81"><span class="nav-number">5.3.</span> <span class="nav-text">销毁</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%87%A0%E7%A7%8D%E5%B8%B8%E8%A7%81%E8%BF%87%E7%A8%8B%E7%9A%84%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E8%BF%87%E7%A8%8B"><span class="nav-number">5.4.</span> <span class="nav-text">几种常见过程的生命周期过程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%88%B6-widget-%E7%8A%B6%E6%80%81%E5%8F%98%E5%8C%96"><span class="nav-number">5.4.1.</span> <span class="nav-text">父 widget 状态变化</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Navigator-push"><span class="nav-number">5.4.2.</span> <span class="nav-text">Navigator.push</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Navigator-pop"><span class="nav-number">5.4.3.</span> <span class="nav-text">Navigator.pop</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#App-%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F"><span class="nav-number">6.</span> <span class="nav-text">App 生命周期</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E5%9B%9E%E8%B0%83"><span class="nav-number">6.1.</span> <span class="nav-text">生命周期回调</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Wyatex"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">Wyatex</p>
  <div class="site-description" itemprop="description">这里是我用来做笔记的网站哟~</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">155</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">26</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">97</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="https://github.com/wyatex" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;wyatex" rel="noopener me" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:wyatex@qq.com" title="E-Mail → mailto:wyatex@qq.com" rel="noopener me" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>

        </div>
      </div>
    </div>

    
    <div class="sidebar-inner sidebar-blogroll">
      <div class="links-of-blogroll animated">
        <div class="links-of-blogroll-title"><i class="fa fa-globe fa-fw"></i>
          链接
        </div>
        <ul class="links-of-blogroll-list">
            <li class="links-of-blogroll-item">
              <a href="https://antfu.me/" title="https:&#x2F;&#x2F;antfu.me&#x2F;" rel="noopener" target="_blank">Anthony Fu</a>
            </li>
            <li class="links-of-blogroll-item">
              <a href="https://www.codesky.me/" title="https:&#x2F;&#x2F;www.codesky.me&#x2F;" rel="noopener" target="_blank">CodeSky</a>
            </li>
            <li class="links-of-blogroll-item">
              <a href="https://learn.lianglianglee.com/" title="https:&#x2F;&#x2F;learn.lianglianglee.com&#x2F;" rel="noopener" target="_blank">技术文章摘抄</a>
            </li>
        </ul>
      </div>
    </div>
        <div class="pjax">
        <div class="sidebar-inner sidebar-post-related">
          <div class="animated">
              <div class="links-of-blogroll-title"><i class="fa fa-signs-post fa-fw"></i>
    相关文章
  </div>
  <ul class="popular-posts">
    <li class="popular-posts-item">
      <a class="popular-posts-link" href="/Flutter/Ubuntu%E6%90%AD%E5%BB%BAFlutter%E5%BC%80%E5%8F%91%E7%8E%AF%E5%A2%83/" rel="bookmark">
        <time class="popular-posts-time">2022-10-23</time>
        <br>
      Ubuntu搭建Flutter开发环境
      </a>
    </li>
    <li class="popular-posts-item">
      <a class="popular-posts-link" href="/Flutter/FlutterCourse-1/" rel="bookmark">
        <time class="popular-posts-time">2023-10-28</time>
        <br>
      面向Vue开发者的Flutter教程（1）
      </a>
    </li>
    <li class="popular-posts-item">
      <a class="popular-posts-link" href="/Flutter/flutter%E7%9A%84%E4%B8%80%E4%BA%9B%E5%9D%91-1/" rel="bookmark">
        <time class="popular-posts-time">2022-11-22</time>
        <br>
      flutter的一些坑（1）
      </a>
    </li>
  </ul>

          </div>
        </div>
        </div>
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wyatex.online/Flutter/flutterNote1/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="Wyatex">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Wyatex`s blog">
      <meta itemprop="description" content="这里是我用来做笔记的网站哟~">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="flutter快速入门笔记（1） | Wyatex`s blog">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          flutter快速入门笔记（1）
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2022-11-04 14:58:06" itemprop="dateCreated datePublished" datetime="2022-11-04T14:58:06+08:00">2022-11-04</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2023-09-15 18:16:22" itemprop="dateModified" datetime="2023-09-15T18:16:22+08:00">2023-09-15</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/Flutter/" itemprop="url" rel="index"><span itemprop="name">Flutter</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv">
      <span class="post-meta-item-icon">
        <i class="far fa-eye"></i>
      </span>
      <span class="post-meta-item-text">阅读次数：</span>
      <span id="busuanzi_value_page_pv"></span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><p>本系列不包含 Dart 语法笔记，以掌握 Dart 语法为前提记录。不懂可以百度搜一下Dart快速入门教程，如果你本来就懂js，基本可以一两小时内掌握Dart的语法，比如看下<a target="_blank" rel="noopener" href="https://book.flutterchina.club/chapter1/dart.html">Flutter实战上的Dart简介</a></p>
<span id="more"></span>

<h1 id="启动"><a href="#启动" class="headerlink" title="启动"></a>启动</h1><p>flutter 入口文件 main.dart</p>
<figure class="highlight dart"><figcaption><span>main.dart</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> <span class="string">&#x27;package:flutter/material.dart&#x27;</span>; <span class="comment">// 导入md风格组件</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">void</span> main() =&gt; runApp(MyApp()); <span class="comment">// 启动flutter</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyApp</span> <span class="keyword">extends</span> <span class="title">StatelessWidget</span> </span>&#123;</span><br><span class="line">  <span class="meta">@override</span></span><br><span class="line">  Widget build(BuildContext context) =&gt; MaterialApp(home: MyHomePage(title: <span class="string">&#x27;Flutter Demo Home Page&#x27;</span>));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyHomePage</span> <span class="keyword">extends</span> <span class="title">StatefulWidget</span> </span>&#123;</span><br><span class="line">  MyHomePage(&#123;Key key, <span class="keyword">this</span>.title&#125;) : <span class="keyword">super</span>(key: key);</span><br><span class="line">  <span class="keyword">final</span> <span class="built_in">String</span> title;</span><br><span class="line">  <span class="meta">@override</span></span><br><span class="line">  _MyHomePageState createState() =&gt; _MyHomePageState();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">_MyHomePageState</span> <span class="keyword">extends</span> <span class="title">State</span>&lt;<span class="title">MyHomePage</span>&gt; </span>&#123;</span><br><span class="line">  Widget build(BuildContext context) =&gt; &#123;...&#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>用 vue3 项目来类比，main.dart 相当于 main.ts&#x2F;js。runApp 相当于 createApp，MyApp 相当传进 createApp 的根组件，MyHomePage 相当于首页组件。</p>
<p>build 相当于 vue 的 h 或者 createVNode。</p>
<h1 id="flutter-的三棵树"><a href="#flutter-的三棵树" class="headerlink" title="flutter 的三棵树"></a>flutter 的三棵树</h1><p>flutter 的三棵树分别是 widget、element、renderObject 树。<br>用 vue 类比就是 widget-&gt;template&#x2F;jsx、element-&gt;虚拟 dom、renderObject-&gt;浏览器 dom 树。</p>
<p>可能不太准确，但是适合对 flutter 没有概念的人理解 flutter 整个渲染原理。</p>
<h1 id="StatelessWidget"><a href="#StatelessWidget" class="headerlink" title="StatelessWidget"></a>StatelessWidget</h1><p>StatelessWidget 非常好理解，就是一个不可变的，没有状态的 widget，用 vue 类比就是一个.vue 文件里面只写个 template 标签，或者再 import 别的组件然后用到 template 上，而且没用 data 函数定义组件的状态。<br>比如上面的：</p>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyApp</span> <span class="keyword">extends</span> <span class="title">StatelessWidget</span> </span>&#123;</span><br><span class="line">  <span class="meta">@override</span></span><br><span class="line">  Widget build(BuildContext context) =&gt; MaterialApp(home: MyHomePage(title: <span class="string">&#x27;Flutter Demo Home Page&#x27;</span>));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>相当于 vue 的这样的代码</p>
<figure class="highlight js"><figcaption><span>MyApp.vue</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&lt;template&gt;</span><br><span class="line">    &lt;div&gt;</span><br><span class="line">        <span class="language-xml"><span class="tag">&lt;<span class="name">p</span>&gt;</span>HelloWorld<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span></span><br><span class="line">    &lt;div&gt;</span><br><span class="line">&lt;/template&gt;</span><br><span class="line"><span class="language-xml"><span class="tag">&lt;<span class="name">script</span> <span class="attr">setup</span>&gt;</span></span></span><br><span class="line"><span class="language-xml"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span></span><br></pre></td></tr></table></figure>

<p>vue3编译器会发现这个div和p是静态的，会编译成_hoisted_1、_hoisted_2 这样的对象，提升到render函数之外，组件实例化时只会构建一次，避免每次执行render都要重新构建。</p>
<h1 id="StatefulWidget"><a href="#StatefulWidget" class="headerlink" title="StatefulWidget"></a>StatefulWidget</h1><p>在 flutter 中，Widget 是不可变的，发生变化时需要销毁重建，所以谈不上状态。既然 widget 不可变，那则么实现有状态的 widget 呢，那就是用另一个类帮我们代理生成 widget，每次状态发生改变，那就让代理类生成一个新的 widget。</p>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyHomePage</span> <span class="keyword">extends</span> <span class="title">StatefulWidget</span> </span>&#123; <span class="comment">// 其实StatefulWidget和StatelessWidget一样不可变</span></span><br><span class="line">  MyHomePage(&#123;Key key, <span class="keyword">this</span>.title&#125;) : <span class="keyword">super</span>(key: key);</span><br><span class="line">  <span class="keyword">final</span> <span class="built_in">String</span> title;</span><br><span class="line">  <span class="meta">@override</span></span><br><span class="line">  _MyHomePageState createState() =&gt; _MyHomePageState(); <span class="comment">// 但是Statefule的子widget由State代理生成，也就是Statefule的子widget可以动态切换</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">_MyHomePageState</span> <span class="keyword">extends</span> <span class="title">State</span>&lt;<span class="title">MyHomePage</span>&gt; </span>&#123; <span class="comment">// State类代理里如果状态发生改变就生成新的widget交给外面的StatefulWidget</span></span><br><span class="line">  Widget build(BuildContext context) =&gt; &#123;...&#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>用 vue 来理解：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; h &#125; <span class="keyword">from</span> <span class="string">&#x27;vue&#x27;</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">  <span class="title function_">setup</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="comment">// 类似createState</span></span><br><span class="line">    <span class="comment">// do sth</span></span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">      <span class="comment">// ...</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">render</span>: <span class="function">() =&gt;</span> <span class="title function_">h</span>(<span class="string">&#x27;...&#x27;</span>), <span class="comment">// 类似build，当主动修改组件的状态时，就重新调用这个render</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>总结：<strong>StatefulWidget 不是万金油，要慎用</strong>。Widget 是不可变的，更新则意味着销毁 + 重建（build）。StatelessWidget 是静态的，一旦创建则无需更新；而对于 StatefulWidget 来说，在 State 类中调用 setState 方法更新数据，会触发视图的销毁和重建，也将间接地触发其每个子 Widget 的销毁和重建。</p>
</blockquote>
<p>所以 StatefulWidget 要用对地方，比如如果根 Widget 是 StatefulWidget 的话，那么他状态一改变整个 widget 树都要重建，可想而知对性能的影响有多严重。</p>
<h1 id="生命周期"><a href="#生命周期" class="headerlink" title="生命周期"></a>生命周期</h1><p>对于这种数据驱动的框架，一般都会提供生命周期函数钩子，像 vue 的 onMounted、onUpdated 等等。State 的生命周期可以分为 3 个阶段：创建（插入视图树）、更新（在视图树中存在）、销毁（从视图树中移除）</p>
<h2 id="创建"><a href="#创建" class="headerlink" title="创建"></a>创建</h2><p>State 初始化时会依次执行 ：构造方法（上面的 createState 方法） -&gt; initState（像 vue 的 create 过程，生命周期只调用一次，用于设置默认值） -&gt; didChangeDependencies -&gt; build，随后完成页面渲染。</p>
<h2 id="更新"><a href="#更新" class="headerlink" title="更新"></a>更新</h2><p>Widget 的状态更新，主要由 3 个方法触发：</p>
<ul>
<li>setState：相当于 vue 的 this.xxx &#x3D; xxx，告诉代理，状态发生了改变，需要去更新视图</li>
<li>didChangeDependencies：依赖值发生改变，比如 vue 的全局状态改变，如果组件依赖了全局状态，那么也需要去更新视图</li>
<li>didUpdateWidget：比如父 Widget 状态发生改变，会触发子组件的这个方法，还有热更新也是系统会使用这个方法去更新视图。</li>
</ul>
<p>一旦这三个方法被调用，Flutter 随后就会销毁老 Widget，并调用 build 方法重建 Widget。</p>
<h2 id="销毁"><a href="#销毁" class="headerlink" title="销毁"></a>销毁</h2><p>组件被移除，或是页面销毁的时候，系统会调用 deactivate 和 dispose，来移除或销毁组件。相当于 vue 组件的 unmounte 过程，貌似vue组件卸载和销毁是一个周期内执行完，并提供beforeUnmount和unmounted钩子函数。</p>
<h2 id="几种常见过程的生命周期过程"><a href="#几种常见过程的生命周期过程" class="headerlink" title="几种常见过程的生命周期过程"></a>几种常见过程的生命周期过程</h2><h3 id="父-widget-状态变化"><a href="#父-widget-状态变化" class="headerlink" title="父 widget 状态变化"></a>父 widget 状态变化</h3><p>父 widget：setState -&gt; build<br>子 widget: didUpdateWidget -&gt; build</p>
<h3 id="Navigator-push"><a href="#Navigator-push" class="headerlink" title="Navigator.push"></a>Navigator.push</h3><p>下一个 Widget：构建方法 -&gt; (initState) -&gt; didChangeDependencies -&gt; build<br>当前 Widget: deactivate -&gt; build</p>
<h3 id="Navigator-pop"><a href="#Navigator-pop" class="headerlink" title="Navigator.pop"></a>Navigator.pop</h3><p>上一个 Widget：deactivate(还是调用 deactivate，设计的有点奇怪) -&gt; build<br>当前 Widget: deactivate -&gt; dispose</p>
<h1 id="App-生命周期"><a href="#App-生命周期" class="headerlink" title="App 生命周期"></a>App 生命周期</h1><p>除了 widget 的生命周期，app 也有生命周期，在 widget 中可以通过<a target="_blank" rel="noopener" href="https://api.flutter.dev/flutter/widgets/WidgetsBindingObserver-class.html">WidgetsBindingObserver</a>类来调用 App 的生命周期钩子：</p>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">WidgetsBindingObserver</span> </span>&#123;</span><br><span class="line">  <span class="comment">// 页面 pop</span></span><br><span class="line">  Future&lt;<span class="built_in">bool</span>&gt; didPopRoute() =&gt; Future&lt;<span class="built_in">bool</span>&gt;.value(<span class="keyword">false</span>);</span><br><span class="line">  <span class="comment">// 页面 push</span></span><br><span class="line">  Future&lt;<span class="built_in">bool</span>&gt; didPushRoute(<span class="built_in">String</span> route) =&gt; Future&lt;<span class="built_in">bool</span>&gt;.value(<span class="keyword">false</span>);</span><br><span class="line">  <span class="comment">// 系统窗口相关改变回调，如旋转</span></span><br><span class="line">  <span class="keyword">void</span> didChangeMetrics() &#123; &#125;</span><br><span class="line">  <span class="comment">// 文本缩放系数变化</span></span><br><span class="line">  <span class="keyword">void</span> didChangeTextScaleFactor() &#123; &#125;</span><br><span class="line">  <span class="comment">// 系统亮度变化</span></span><br><span class="line">  <span class="keyword">void</span> didChangePlatformBrightness() &#123; &#125;</span><br><span class="line">  <span class="comment">// 本地化语言变化</span></span><br><span class="line">  <span class="keyword">void</span> didChangeLocales(<span class="built_in">List</span>&lt;Locale&gt; locale) &#123; &#125;</span><br><span class="line">  <span class="comment">//App 生命周期变化</span></span><br><span class="line">  <span class="keyword">void</span> didChangeAppLifecycleState(AppLifecycleState state) &#123; &#125;</span><br><span class="line">  <span class="comment">// 内存警告回调</span></span><br><span class="line">  <span class="keyword">void</span> didHaveMemoryPressure() &#123; &#125;</span><br><span class="line">  <span class="comment">//Accessibility 相关特性回调</span></span><br><span class="line">  <span class="keyword">void</span> didChangeAccessibilityFeatures() &#123;&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="生命周期回调"><a href="#生命周期回调" class="headerlink" title="生命周期回调"></a>生命周期回调</h2><p>didChangeAppLifecycleState 回调函数中，有一个参数类型为 AppLifecycleState 的枚举类，这个枚举类是 Flutter 对 App 生命周期状态的封装。它的常用状态包括 resumed、inactive、paused 这三个。</p>
<ul>
<li>resumed：可见的，并能响应用户的输入。</li>
<li>inactive：处在不活动状态，无法处理用户响应。</li>
<li>paused：不可见并不能响应用户的输入，但是在后台继续活动中。</li>
</ul>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">_MyHomePageState</span> <span class="keyword">extends</span> <span class="title">State</span>&lt;<span class="title">MyHomePage</span>&gt;  <span class="title">with</span> <span class="title">WidgetsBindingObserver</span></span>&#123;</span><br><span class="line">  <span class="meta">@override</span></span><br><span class="line">  <span class="meta">@mustCallSuper</span></span><br><span class="line">  <span class="keyword">void</span> initState() &#123;</span><br><span class="line">    <span class="keyword">super</span>.initState();</span><br><span class="line">    WidgetsBinding.instance.addObserver(<span class="keyword">this</span>);<span class="comment">// 注册监听器</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="meta">@override</span></span><br><span class="line">  <span class="meta">@mustCallSuper</span></span><br><span class="line">  <span class="keyword">void</span> dispose()&#123;</span><br><span class="line">    <span class="keyword">super</span>.dispose();</span><br><span class="line">    WidgetsBinding.instance.removeObserver(<span class="keyword">this</span>);<span class="comment">// 移除监听器</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="meta">@override</span></span><br><span class="line">  <span class="keyword">void</span> didChangeAppLifecycleState(AppLifecycleState state) <span class="keyword">async</span> &#123;</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;<span class="subst">$state</span>&quot;</span>);</span><br><span class="line">    <span class="keyword">if</span> (state == AppLifecycleState.resumed) &#123;</span><br><span class="line">      <span class="comment">//do sth</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>以上就是 flutter 的基本知识了，如果会 vue 的话入手 flutter 也是简简单单。如果点赞多就继续写一下布局、组件的快速入门教程XD</p>

    </div>

    
    
    

    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>Wyatex
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="https://wyatex.online/Flutter/flutterNote1/" title="flutter快速入门笔记（1）">https://wyatex.online/Flutter/flutterNote1/</a>
  </li>
  <li class="post-copyright-license">
      <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

          <div class="post-tags">
              <a href="/tags/%E5%89%8D%E7%AB%AF/" rel="tag"># 前端</a>
              <a href="/tags/%E7%AC%94%E8%AE%B0/" rel="tag"># 笔记</a>
              <a href="/tags/Flutter/" rel="tag"># Flutter</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/%E5%89%8D%E7%AB%AF/%E8%A7%A3%E5%86%B3mobx-miniprogram%E5%9C%A8TS%E4%B8%8B%E7%9A%84%E4%B8%80%E4%BA%9B%E5%B0%8F%E9%97%AE%E9%A2%98/" rel="prev" title="解决mobx-miniprogram在TS下的一些小问题">
                  <i class="fa fa-angle-left"></i> 解决mobx-miniprogram在TS下的一些小问题
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/Flutter/flutter%E7%9A%84%E4%B8%80%E4%BA%9B%E5%9D%91-1/" rel="next" title="flutter的一些坑（1）">
                  flutter的一些坑（1） <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 2019 – 
    <span itemprop="copyrightYear">2024</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">Wyatex</span>
  </div>
<div class="busuanzi-count">
    <span class="post-meta-item" id="busuanzi_container_site_uv">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-item" id="busuanzi_container_site_pv">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>

    </div>
  </footer>

  
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script size="300" alpha="0.6" zIndex="-1" src="/lib/ribbon.js/dist/ribbon.min.js"></script>
  <script src="/lib/animejs/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="/lib/@next-theme/pjax/pjax.min.js" integrity="sha256-vxLn1tSKWD4dqbMRyv940UYw4sXgMtYcK6reefzZrao=" crossorigin="anonymous"></script>
  <script src="/lib/@fancyapps/ui/dist/fancybox/fancybox.umd.js" integrity="sha256-q8XkJ6dj5VwSvzI8+nATCHHQG+Xv/dAZBCgqmu93zOY=" crossorigin="anonymous"></script>
  <script src="/lib/lozad/dist/lozad.min.js" integrity="sha256-mOFREFhqmHeQbXpK2lp4nA3qooVgACfh88fpJftLBbc=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  <script src="/lib/hexo-generator-searchdb/dist/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>




  <script src="/js/third-party/fancybox.js"></script>



  
  <script data-pjax async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>





</body>
</html>
